package com.wei.file.serve;

import com.wei.file.model.FileParseResult;
import com.wei.file.serve.impl.LinuxFileService;
import com.wei.file.serve.impl.WindowFileService;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public interface FileService {


    /**
     * 是不是一个快捷方式
     */
    boolean isLink(File file);


    static FileService create() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("windows")) {
            return new WindowFileService();
        } else if (osName.contains("linux")) {
            return new LinuxFileService();
        }
//      当前操作系统不是 Windows 也不是 Linux。
        return new LinuxFileService();
    }
    private Charset getCharset(String charsetStr) {
        Charset defaultCharset = StandardCharsets.UTF_8;
        if (charsetStr == null || charsetStr.equals("UTF_8")) {
            return defaultCharset;
        }
        if (charsetStr.equals("US_ASCII"))
            return StandardCharsets.US_ASCII;
        if (charsetStr.equals("ISO_8859_1"))
            return StandardCharsets.ISO_8859_1;
        if (charsetStr.equals("UTF_16"))
            return StandardCharsets.UTF_16;
        if (charsetStr.equals("GBK"))
            return Charset.forName("gbk");
        if (charsetStr.equals("UNICODE"))
            return Charset.forName("unicode");
        return defaultCharset;
    }



    default FileParseResult readFileString(Path path, String charsetStr) throws RuntimeException {
        String code = "";
        boolean charSetError = false;
        if("BINARY".equals(charsetStr)){
            try {
                code =  this.decodeToHex(Files.readAllBytes(path));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }else{
            Charset charset = this.getCharset(charsetStr);
            try {
                code = Files.readString(path, charset);
            } catch (Throwable e) {
                charSetError = true;
                byte[] bytes;
                try {
                    bytes = Files.readAllBytes(path);
                    code = new String(bytes, charset);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
        if (code.isEmpty() && path.toFile().length() != 0) {
            charSetError = true;
        }
        return new FileParseResult(charSetError, code);
    }
    default String decodeToHex(byte[] binaryData) {
        StringBuilder hexStringBuilder = new StringBuilder();
        for (byte b : binaryData) {
            hexStringBuilder.append(String.format("%02X ", b));
        }
        return hexStringBuilder.toString();
    }
}